﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Data;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;

namespace QuanLyKho.QuanLyKho
{
    public partial class Kho_Themvattu : Form
    {
        public static string MaID = "0";
        public static string TenKho = string.Empty;

        public Kho_Themvattu()
        {
            InitializeComponent();
            LoadData();
        }

        public void LoadData()
        {
            luLoaiVatTu.Properties.DataSource = DataAll.SelectAll("Kho_LoaiVatTu", "IDLoaiVatTu,TenLoaiVatTu", "");
            luLoaiVatTu.Properties.Columns.Add(new LookUpColumnInfo("TenLoaiVatTu"));
            luLoaiVatTu.Properties.Columns.Add(new LookUpColumnInfo("IDLoaiVatTu"));
            luLoaiVatTu.Properties.DisplayMember = "TenLoaiVatTu";
            luLoaiVatTu.Properties.ValueMember = "IDLoaiVatTu";
            luLoaiVatTu.Properties.Columns["IDLoaiVatTu"].Visible = false;
            luLoaiVatTu.Properties.NullText = "- Chọn loại vật tư -";
            //luLoaiVatTu.Properties.TextEditStyle = TextEditStyles.Standard;
            luLoaiVatTu.Properties.ShowHeader = false;

            luNhomHang.Properties.DataSource = DataAll.SelectAll("PhongMau_NhomHang", "IdNhomHang,TenNhom", "");
            luNhomHang.Properties.Columns.Add(new LookUpColumnInfo("IdNhomHang"));
            luNhomHang.Properties.Columns.Add(new LookUpColumnInfo("TenNhom"));
            luNhomHang.Properties.DisplayMember = "TenNhom";
            luNhomHang.Properties.ValueMember = "IdNhomHang";
            luNhomHang.Properties.Columns["IdNhomHang"].Visible = false;
            luNhomHang.Properties.NullText = "- Chọn nhóm hàng -";
            //luNhomHang.Properties.TextEditStyle = TextEditStyles.Standard;
            luNhomHang.Properties.ShowHeader = false;

            luMaDangAnh.Properties.DataSource = DataAll.SelectAll("DkChung_HinhAnh", "MaAnh", " WHERE Loai = '1'");
            luMaDangAnh.Properties.Columns.Add(new LookUpColumnInfo("MaAnh"));
            //luMaDangAnh.Properties.Columns.Add(new LookUpColumnInfo("IDHinhAnh"));
            luMaDangAnh.Properties.DisplayMember = "MaAnh";
            luMaDangAnh.Properties.ValueMember = "MaAnh";
            //luMaDangAnh.Properties.Columns["MaAnh"].Visible = false;
            luMaDangAnh.Properties.NullText = "--- Chọn vật tư ---";
            luMaDangAnh.Properties.TextEditStyle = TextEditStyles.Standard;
            luMaDangAnh.Properties.ShowHeader = false;

            luDonVi.Properties.DataSource = DataAll.SelectAll("DkChung_DonVi", "TenDonVi", "");
            luDonVi.Properties.Columns.Add(new LookUpColumnInfo("TenDonVi"));
            luDonVi.Properties.DisplayMember = "TenDonVi";
            luDonVi.Properties.ValueMember = "TenDonVi";
            luDonVi.Properties.NullText = "Chọn đơn vị tính";
            //luDonVi.Properties.TextEditStyle = TextEditStyles.Standard;
            luDonVi.Properties.ShowHeader = false;

            luMauSac.Properties.DataSource = DataAll.SelectAll("DkChung_MauSac", "TenMauSac", "");
            luMauSac.Properties.Columns.Add(new LookUpColumnInfo("TenMauSac"));
            luMauSac.Properties.DisplayMember = "TenMauSac";
            luMauSac.Properties.ValueMember = "TenMauSac";
            luMauSac.Properties.NullText = "Chọn màu sắc";
            //luMauSac.Properties.TextEditStyle = TextEditStyles.Standard;
            luMauSac.Properties.ShowHeader = false;

            luKhoHang.Properties.DataSource = DataAll.SelectAll("DkChung_Kho", "TenKho", "");
            luKhoHang.Properties.Columns.Add(new LookUpColumnInfo("TenKho"));
            luKhoHang.Properties.DisplayMember = "TenKho";
            luKhoHang.Properties.ValueMember = "TenKho";
            luKhoHang.Properties.NullText = "Chọn nhà sản xuất";
            //luKhoHang.Properties.TextEditStyle = TextEditStyles.Standard;
            luKhoHang.Properties.ShowHeader = false;

            txtNguoiTao.Text = Main.UserID;

            if (MaID != "0")
            {
                SetData();
            }
        }

        public void SetData()
        {
            var data = DataAll.SelectAll(TenKho == "DuKien" ? "Kho_VatTuDuKien" : "Kho_VatTu", "*", TenKho == "DuKien" ? " WHERE IDVatTuDuKien=" + MaID : " WHERE IDVatTu=" + MaID);
            txtTen.Text = data.Rows[0]["TenVatTu"].ToString();
            txtDonGia.Text = data.Rows[0]["DonGia"].ToString();
            txtSoLuong.Text = data.Rows[0]["SoLuong"].ToString();
            luMaDangAnh.EditValue = data.Rows[0]["MaAnh"].ToString();
            luLoaiVatTu.EditValue = data.Rows[0]["IDLoaiVatTu"].ToString();
            luDonVi.EditValue = data.Rows[0]["DonVi"].ToString();
            luMauSac.EditValue = data.Rows[0]["MauSac"].ToString();
            luKhoHang.EditValue = data.Rows[0]["NhaSX"].ToString();
            txtGhiChu.Text = data.Rows[0]["GhiChu"].ToString();
            txtMoTa.Text = data.Rows[0]["MoTa"].ToString();
            txtKhoGDS.Text = data.Rows[0]["KhoGSD"].ToString();
            txtQCGiac.Text = data.Rows[0]["QCGiac"].ToString();
            txtSoLuongToiDa.Text = data.Rows[0]["SLToiDa"].ToString();
            txtSoLuongToiThieu.Text = data.Rows[0]["SLToiThieu"].ToString();
            luNhomHang.EditValue = data.Rows[0]["IdNhomHang"].ToString();
            txtNguoiTao.Text = data.Rows[0]["NguoiTao"].ToString();
            txtKhoVai.Text = data.Rows[0]["KhoVai"].ToString();
            LoadImage();
            luMaDangAnh.Enabled = false;
            txtSoLuong.Enabled = false;
        }

        public void LoadImage()
        {
            var data = DataAll.SelectAll("DkChung_HinhAnh", "*", " WHERE MaAnh='" + luMaDangAnh.EditValue + "'");
            if (data.Rows.Count > 0)
            {
                var content = (byte[])data.Rows[0]["Anh"];
                if (content != null)
                {
                    Image newImage;
                    using (var ms = new MemoryStream(content, 0, content.Length))
                    {
                        ms.Write(content, 0, content.Length);
                        newImage = Image.FromStream(ms, true);
                    }
                    pbAnhKho.Image = newImage;
                }
                else
                {
                    pbAnhKho.Image = null;
                }
            }
            else
            {
                MessageBox.Show("Không tìm thấy mã ảnh", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void bntLuuLai_Click(object sender, EventArgs e)
        {
            if (!ValidateForm())
                return;
            if (MaID != "0")
            {
                string message = string.Empty;
                if (TenKho == "ThucTe")
                {
                    message = DataAll.Update("Kho_VatTu", "IDLoaiVatTu=" + luLoaiVatTu.EditValue + ",MaVatTu=N'" + luMaDangAnh.EditValue
                    + "',TenVatTu=N'" + txtTen.Text + "',MaAnh=N'" + luMaDangAnh.EditValue + "',DonGia=" + SplipSo(txtDonGia.Text)
                    + ",SoLuong=" + SplipSo(txtSoLuong.Text) + ",DonVi=N'" + luDonVi.EditValue + "',MauSac=N'" + luMauSac.EditValue
                    + "',KhoGSD=" + SplipSo(txtKhoGDS.Text) + ",QCGiac=N'" + txtQCGiac.Text + "',MoTa=N'" + txtMoTa.Text
                    + "',GhiChu=N'" + txtGhiChu.Text + "',KhoVai = N'" + txtKhoVai.Text + "',IdNhomHang = " + luNhomHang.EditValue
                    + ",SLToiDa = " + SplipSo(txtSoLuongToiDa.Text) + ",SLToiThieu =" + SplipSo(txtSoLuongToiThieu.Text)
                    + ",NguoiTao = N'" + txtNguoiTao.Text + "', NhaSX = N'" + luKhoHang.Text + "' WHERE IDVatTu =" + MaID);
                }
                if (TenKho == "DuKien")
                {
                    message = DataAll.Update("Kho_VatTuDuKien", "IDLoaiVatTu=" + luLoaiVatTu.EditValue + ",MaVatTu=N'" + luMaDangAnh.EditValue
                    + "',TenVatTu=N'" + txtTen.Text + "',MaAnh=N'" + luMaDangAnh.EditValue + "',DonGia=" + SplipSo(txtDonGia.Text)
                    + ", SoLuong=" + SplipSo(txtSoLuong.Text) + ",DonVi=N'" + luDonVi.EditValue + "',MauSac=N'" + luMauSac.EditValue
                    + "',KhoGSD=" + SplipSo(txtKhoGDS.Text) + ",QCGiac=N'" + txtQCGiac.Text + "',MoTa=N'" + txtMoTa.Text
                    + "',GhiChu=N'" + txtGhiChu.Text + "',KhoVai = N'" + txtKhoVai.Text + "',IdNhomHang = " + luNhomHang.EditValue
                    + ",SLToiDa = " + SplipSo(txtSoLuongToiDa.Text) + ",SLToiThieu =" + SplipSo(txtSoLuongToiThieu.Text)
                    + ",NguoiTao = N'" + txtNguoiTao.Text + "', NhaSX = N'" + luKhoHang.Text +"' WHERE IDVatTuDuKien =" + MaID);
                }
                MessageBox.Show(message.Equals("success") ? "Sửa vật tư thành công" : message, "Message",
                            MessageBoxButtons.OK,
                            message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                Close();
            }
            else
            {
                //string message = DataAll.InsertAll("Kho_VatTu", luLoaiVatTu.EditValue + "," + luMaDangAnh.EditValue + "," + txtTen.Text
                //+ "," + luMaDangAnh.EditValue + "," + txtDonGia.Text + "," + txtSoLuong.Text + "," + luDonVi.EditValue + "," + luMauSac.EditValue
                //+ "," + txtKhoGDS.Text + "," + txtQCGiac.Text + "," + txtMoTa.Text + "," + txtGhiChu.Text);
                DataTable maxID = DataAll.SelectCustomer("INSERT INTO [Kho_VatTu] VALUES("
                    + luLoaiVatTu.EditValue + ",N'" + luMaDangAnh.EditValue + "',N'" + txtTen.Text + "','" + luMaDangAnh.EditValue
                    + "'," + SplipSo(txtDonGia.Text) + "," + SplipSo(txtSoLuong.Text) + ",N'" + luDonVi.EditValue + "',N'" + luMauSac.EditValue + "',N'"
                    + SplipSo(txtKhoGDS.Text) + "',N'" + txtQCGiac.Text + "',N'" + txtMoTa.Text + "',N'" + txtGhiChu.Text + "',N'" + txtKhoVai.Text + "'," + luNhomHang.EditValue
                    + "," + SplipSo(txtSoLuongToiDa.Text) + "," + SplipSo(txtSoLuongToiThieu.Text) + ",N'" + txtNguoiTao.Text + "',N'" + luKhoHang.Text + "') SELECT MAX(IDVatTu) FROM [Kho_VatTu]");

                DataAll.InsertAll("Kho_VatTuDuKien", luLoaiVatTu.EditValue + "," + luMaDangAnh.EditValue + "," + txtTen.Text
                + "," + luMaDangAnh.EditValue + "," + SplipSo(txtDonGia.Text) + "," + SplipSo(txtSoLuong.Text) + "," + luDonVi.EditValue + "," + luMauSac.EditValue
                + "," + SplipSo(txtKhoGDS.Text) + "," + txtQCGiac.Text + "," + txtMoTa.Text + "," + txtGhiChu.Text + "," + txtKhoVai.Text + "," + luNhomHang.EditValue
                + "," + SplipSo(txtSoLuongToiDa.Text) + "," + SplipSo(txtSoLuongToiThieu.Text) + "," + txtNguoiTao.Text+"," + luKhoHang.Text);
                DataTable dtKho = DataAll.SelectAll("Kho_KhoHang", "*", "");
                if (dtKho.Rows.Count > 0)
                {
                    for (int i = 0; i < dtKho.Rows.Count; i++)
                    {
                        DataAll.InsertAll("Kho_KhoHang_VatTu", maxID.Rows[0][0] + "," + dtKho.Rows[i]["IDKhoHang"] + ",0");
                    }
                }

                MessageBox.Show("Thêm vật tư thành công", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                ResetForm();
            }
        }

        private void bntThoat_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void luMaDangAnh_EditValueChanged(object sender, EventArgs e)
        {
            var lucheck = (LookUpEdit)sender;
            if (lucheck.ItemIndex >= 0)
            {
                LoadImage();
            }
        }

        private bool ValidateForm()
        {
            var dataCheck = DataAll.SelectAll("Kho_VatTu", "MaVatTu", " WHERE MaVatTu =N'" + luMaDangAnh.EditValue + "'");
            if (dataCheck.Rows.Count > 0 && MaID == "0")
            {
                MessageBox.Show("Đã có vật tư trong kho!", "Lỗi nhập dữ liệu", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (luMaDangAnh.EditValue == null)
            {
                MessageBox.Show("Vui lòng chọn vật tư !", "Lỗi nhập dữ liệu", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (string.IsNullOrEmpty(txtTen.Text))
            {
                MessageBox.Show("Vui lòng nhập tên vật tư !", "Lỗi nhập dữ liệu", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (luLoaiVatTu.EditValue == null)
            {
                MessageBox.Show("Vui lòng chọn loại vật tư !", "Lỗi nhập dữ liệu", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (string.IsNullOrEmpty(txtDonGia.Text))
            {
                MessageBox.Show("Vui lòng nhập đơn giá !", "Lỗi nhập dữ liệu", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            if (luDonVi.EditValue == null)
            {
                MessageBox.Show("Vui lòng chọn đơn vị !", "Lỗi nhập dữ liệu", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            if (luMauSac.EditValue == null)
            {
                MessageBox.Show("Vui lòng chọn màu sắc !", "Lỗi nhập dữ liệu", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            return true;
        }

        public double SplipSo(string so)
        {
            string[] temp = so.Split(',');
            string tempSo = temp.Aggregate<string, string>(null, (current, t) => current + t);
            if (string.IsNullOrEmpty(tempSo))
            {
                return 0;
            }
            return Convert.ToDouble(tempSo);
        }

        private void ResetForm()
        {
            luMaDangAnh.EditValue = luLoaiVatTu.EditValue = luDonVi.EditValue = luMauSac.EditValue = string.Empty;
            txtTen.Text = txtDonGia.Text = txtSoLuong.Text = txtKhoGDS.Text = txtQCGiac.Text 
                = txtMoTa.Text = txtGhiChu.Text = txtKhoVai.Text = txtSoLuongToiDa.Text = txtSoLuongToiThieu.Text = string.Empty;
        }

        private void txtDonGia_TextChanged(object sender, EventArgs e)
        {
            try
            {
                var culture = new System.Globalization.CultureInfo("en-US");
                double valueBefore = double.Parse(txtDonGia.Text, System.Globalization.NumberStyles.AllowThousands);
                txtDonGia.Text = String.Format(culture, "{0:N0}", valueBefore);
                txtDonGia.Select(txtDonGia.Text.Length, 0);
            }
            catch (Exception)
            {

            }
            if (string.IsNullOrEmpty(txtDonGia.Text))
            {
                txtDonGia.Text = "0";
            }
        }

        private void txtSoLuong_TextChanged(object sender, EventArgs e)
        {
            try
            {
                var culture = new System.Globalization.CultureInfo("en-US");
                double valueBefore = double.Parse(txtSoLuong.Text, System.Globalization.NumberStyles.AllowThousands);
                txtSoLuong.Text = String.Format(culture, "{0:N0}", valueBefore);
                txtSoLuong.Select(txtSoLuong.Text.Length, 0);
            }
            catch (Exception)
            {

            }
            if (string.IsNullOrEmpty(txtSoLuong.Text))
            {
                txtSoLuong.Text = "0";
            }
        }

        private void txtKhoGDS_TextChanged(object sender, EventArgs e)
        {
            try
            {
                var culture = new System.Globalization.CultureInfo("en-US");
                double valueBefore = double.Parse(txtKhoGDS.Text, System.Globalization.NumberStyles.AllowThousands);
                txtKhoGDS.Text = String.Format(culture, "{0:N0}", valueBefore);
                txtKhoGDS.Select(txtKhoGDS.Text.Length, 0);
            }
            catch (Exception)
            {

            }
            if (string.IsNullOrEmpty(txtKhoGDS.Text))
            {
                txtKhoGDS.Text = "0";
            }
        }

        private void txtSoLuongToiDa_TextChanged(object sender, EventArgs e)
        {
            try
            {
                var culture = new System.Globalization.CultureInfo("en-US");
                double valueBefore = double.Parse(txtSoLuongToiDa.Text, System.Globalization.NumberStyles.AllowThousands);
                txtSoLuongToiDa.Text = String.Format(culture, "{0:N0}", valueBefore);
                txtSoLuongToiDa.Select(txtSoLuongToiDa.Text.Length, 0);
            }
            catch (Exception)
            {

            }
            if (string.IsNullOrEmpty(txtSoLuongToiDa.Text))
            {
                txtSoLuongToiDa.Text = "0";
            }
        }

        private void txtSoLuongToiThieu_TextChanged(object sender, EventArgs e)
        {
            try
            {
                var culture = new System.Globalization.CultureInfo("en-US");
                double valueBefore = double.Parse(txtSoLuongToiThieu.Text, System.Globalization.NumberStyles.AllowThousands);
                txtSoLuongToiThieu.Text = String.Format(culture, "{0:N0}", valueBefore);
                txtSoLuongToiThieu.Select(txtSoLuongToiThieu.Text.Length, 0);
            }
            catch (Exception)
            {

            }
            if (string.IsNullOrEmpty(txtSoLuongToiThieu.Text))
            {
                txtSoLuongToiThieu.Text = "0";
            }
        }

    }
}
